package com.supcalls.tool;

import java.util.concurrent.*;

/**
 * CountDownLatch 用于让一个或多个线程等待直到某些操作完成。
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);

        for (int i = 0; i < 3; i++) {
            final int taskId = i;
            new Thread(() -> {
                try {
                    System.out.println("Task " + taskId + " is starting.");
                    Thread.sleep(2000);
                    System.out.println("Task " + taskId + " is finished.");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        latch.await();  // Main thread will wait until latch count is 0
        System.out.println("All tasks are finished.");
    }
}
